import json
from app import db
from flask import Blueprint, render_template, request, url_for, redirect
bp = Blueprint('AdminInformation', __name__, url_prefix='/Admin')
from app.models import Admin
from app.models import Book


#Json序列化
import decimal

class DecimalEncoder(json.JSONEncoder):

    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)

@bp.route('/Information', methods=['GET', 'POST'])
def admin():
    print("I am here")
    admins= Admin.query.all()
    context = {
            'inf': admins
        }
    return render_template('Admin Information.html', **context)



@bp.route('/delete', methods=['GET', 'POST'])
def delete():
    bid = request.form['name']
    example = Admin.query.get(bid)
    print(example)
    db.session.delete(example)
    db.session.commit()
    admins = Admin.query.all()
    print(admins)
    adminLists = [admin.to_dict() for admin in admins]
    print(adminLists)
    return json.dumps(adminLists, cls=DecimalEncoder)

@bp.route('/modify', methods=['GET', 'POST'])
def modify():
    username = request.form['id']
    admins = Admin.query.filter_by(username=int(username)).all()
    print(admins)
    adminLists = [admin.to_dict() for admin in admins]
    print(adminLists)
    return json.dumps(adminLists,cls=DecimalEncoder)

@bp.route('/modifyResult', methods=['PUT'])
def modifyResult():

    username = request.form['username']
    password = request.form['password']


    admin = Admin(username=username, password=password)
    example = Admin.query.get(int(username))
    db.session.delete(example)
    db.session.add(admin)
    db.session.commit()

    admins = Admin.query.all()
    print(admins)
    adminsLists = [admin.to_dict() for admin in admins]
    print(adminsLists)
    return json.dumps(adminsLists,cls=DecimalEncoder)

@bp.route('/search', methods=['GET', 'POST'])
def search():
    data = request.args.get('search')
    example = Admin.query.filter_by(username=int(data))
    context = {
        'inf': example
        }
    return render_template('Admin Information.html', **context)


@bp.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'GET':
        return render_template('addadmin.html')
    else:
        username = request.form['username']
        password = request.form['password']
        admin = Admin(username=username,password=password)
        db.session.add(admin)
        db.session.commit()
    return redirect(url_for('AdminInformation.admin'))

@bp.route('/returnAdmin', methods=['GET', 'POST'])
def returnAdmin():
    admins = Admin.query.all()
    adminLists = [admin.to_dict() for admin in admins]
    return json.dumps(adminLists,cls=DecimalEncoder)